﻿using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Resources;

namespace CL2CDebugToolV2
{
    public static class AppUtils
    {
        private static MemoryMappedFile sharedMemory;
        private static Mutex mutex;

        public static bool IsApplicationAlreadyRunning(string appKey)
        {
            bool isAlreadyRunning = false;

            // 创建命名的互斥量来判断是否已有程序在运行
            mutex = new Mutex(true, appKey, out bool createdNew);

            if (!createdNew)
            {
                isAlreadyRunning = true;
            }
            return isAlreadyRunning;
        }

        public static void CopyEmbeddedResourceToDirectory(string resourceName, string targetFilePath)
        {
            var assembly = Assembly.GetExecutingAssembly();

            Uri resourceUri = new Uri(resourceName, UriKind.RelativeOrAbsolute);
            StreamResourceInfo resourceInfo = Application.GetResourceStream(resourceUri);

            // 格式为：命名空间.文件名，例如 "MyAppNamespace.Resources.MyFile.txt"
            //string resourceFullName = $"{assembly.GetName().Name}.{resourceName}";

            using (Stream resourceStream = resourceInfo.Stream)
            {
                if (resourceStream == null)
                {
                    throw new FileNotFoundException("资源文件未找到: " + resourceName);
                }

                using (FileStream fileStream = new FileStream(targetFilePath, FileMode.Create, FileAccess.Write))
                {
                    resourceStream.CopyTo(fileStream);
                }
            }
        }

        public static string ReadEmbeddedResource(string resourceName)
        {
            Uri resourceUri = new Uri(resourceName, UriKind.RelativeOrAbsolute);
            StreamResourceInfo resourceInfo = Application.GetResourceStream(resourceUri);

            using (Stream resourceStream = resourceInfo.Stream)
            {
                if (resourceStream == null)
                {
                    throw new FileNotFoundException("资源文件未找到: " + resourceName);
                }

                using (StreamReader reader = new StreamReader(resourceStream))
                {
                    return reader.ReadToEnd(); // 读取并返回文本内容
                }
            }
        }

    }
}
